package top.someapp.applib.webview;

import java.util.Map;
import org.json.JSONObject;
import top.someapp.applib.Base;

/**
 * @author zwz
 * Created on 2019-10-16
 */
class JSMethodCall implements Base.MethodCallInfo {

    private final String mClassName;
    private final String method;
    private final Object arguments;

    JSMethodCall(String method, Object arguments) {
        this("", method, arguments);
    }

    JSMethodCall(String className, String method, Object arguments) {
        this.mClassName = className;
        this.method = method;
        this.arguments = arguments;
    }

    @Override
    public String className() {
        return mClassName;
    }

    @Override
    public String methodName() {
        return method;
    }

    @Override
    public boolean hasArgument(String name) {
        if (this.arguments == null) {
            return false;
        } else if (this.arguments instanceof Map) {
            return ((Map) this.arguments).containsKey(name);
        } else if (this.arguments instanceof JSONObject) {
            return ((JSONObject) this.arguments).has(name);
        } else {
            throw new ClassCastException();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T argument(String key) {
        if (this.arguments == null) {
            return null;
        } else if (this.arguments instanceof Map) {
            return (T) ((Map) this.arguments).get(key);
        } else if (this.arguments instanceof JSONObject) {
            return (T) ((JSONObject) this.arguments).opt(key);
        } else {
            throw new ClassCastException();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, ?> namedArguments() {
        if (this.arguments == null) {
            return null;
        } else if (this.arguments instanceof Map) {
            return ((Map) this.arguments);
        } else {
            throw new ClassCastException();
        }
    }

    @Override
    public Object[] ordinalArguments() {
        throw new UnsupportedOperationException();
    }
}
